<?php
if (preg_match ( "/".basename ( __FILE__ )."/", $_SERVER ['PHP_SELF'] )) {
	die ("<h1>Incorrect access</h1>You cannot access this file directly.");
}
class ticket extends Form {
	function ticket(){
		$code = FunctionLib::getParam('code');
		$this->name  = 'ticketForm';
		switch( $code )
		{
			case 'check':
				$this->confirmActive();
				break;
			default:
				$this->home();
				break;
		}
	}
	function confirmActive(){
		global $display;
		$active_ticket_code  	= trim(URL::get('active_ticket_code', ''));
		$ticket_value  	= FunctionLib::getParamInt('ticket_value', 0);
		$ticket_code  	= trim(URL::get('ticket_code', ''));
		$active = (isset($_POST['active'])) ? $_POST['active'] : '';
		$back = (isset($_POST['back'])) ? $_POST['back'] : '';
		if($back){
			Url::redirect('ticket',array('ticket_code'=>$ticket_code));
		}
		//update active
		if($active && $active_ticket_code && $ticket_value > 0){
			$reActive = $this->activeCoupon($active_ticket_code, $ticket_value);
			if($reActive == 'success'){
				Url::redirect('ticket',array('ticket_code'=>$ticket_code));
			}
		}
		else {
			$this->setFormError('', 'Bạn phải nhập giá trị đơn');
		}
		$display->add('ticket_code',$active_ticket_code);
		$display->add('msg',$this->showFormErrorMessages(1));
		$return = $this->beginForm();
        $return .= $display->output('confirm',true,'ticket');
		$return .= $this->endForm();
		echo $return;
	}
	function listTicket(){
        global $display;
        $ticket_code  	= trim(URL::get('ticket_code', ''));
		$active = URL::get('active', '');
		$user = User::getUser(User::id());
		$items = '';
		//echo TIME_NOW+30*24*60*60;
		$totalActive = 'null';
		if($this->errNum == 0){
			//lấy tổng số mã số phiếu đã dùng
			$whereCount  = '';
			if($_SESSION['userDeal']['username'] != 'adminmc'){
				$whereCount   = " AND item_id = 1";
			}
			$totalActive = DB::count(T_TICKET," status = 1 $whereCount");
			if($active){
				$send_ticket_code  	= trim(URL::get('send_ticket_code', ''));
				Url::redirect('ticket',array('code'=>'check','ticket_code'=>$ticket_code,'active_ticket_code'=>$send_ticket_code));
			}
			if($ticket_code){
				
					if($_SESSION['userDeal']['username'] == 'adminmc'){
						$search_value   = " WHERE 1 ";
					}
					else{
						$search_value   = " WHERE item_id = 1";
					}

					$search_value .= " AND  ticket_code = '".$ticket_code."' ";
					$name = 'Mã số phiếu';
							
					$ticket = array();
					$paging = '';
			
					$sql='SELECT * FROM ' . T_TICKET . $search_value ;
					$ticketArr = DB::fetch_all($sql);
					$ticket = array();
					$arrOrderID = array();
					if($ticketArr){
						foreach ($ticketArr as $v ){
							$v['status_text'] = ($v['status'] == 1) ? '<font color="green">Đã sử dụng</font> (lúc '.FunctionLib::dateFormat($v['time_using']).' - kích hoạt bởi: <b>'.$v['approved_user'].'</b>)' : '<font color="red">Chưa sử dụng</font>'; 
							$v['endTimeText'] = ($v['endTime'] > TIME_NOW) ? '<font color="green">Sẽ hết hạn ngày <b>'.FunctionLib::dateFormat($v['endTime']).'</b></font>' : '<font color="red">Đã hết hạn ngày <b>'.FunctionLib::dateFormat($v['endTime']).'</b></font>'; 
							$v['activeButton'] = ($v['status'] != 1 && $v['endTime'] > TIME_NOW);
							$ticket['id'] = $v;
						}
						
						$display->add('ticket',$ticket);
						
						
					}
					else{
						$this->setFormError('',$name.' không đúng. Vui lòng nhập lại hoặc liên hệ với người hỗ trợ để kiểm tra!');
					}
					
				
				$display->add('ticket_code',$ticket_code);
			}
		}
		$display->add('totalActive',$totalActive);
		$display->add('msg',$this->showFormErrorMessages(1));
		//$return = $this->beginForm();
        $return = $display->output('ticket',true,'ticket');
		//$return .= $this->endForm();
		return $return;
    }
	function activeCoupon($ticket_code = '', $ticket_value = 0){
		if($ticket_code){
			$user = User::getUser(User::id());

			$where = '';
			if($_SESSION['userDeal']['username'] != 'adminmc'){
				$where = "item_id =1 AND ";
			}
			$search_value   = " WHERE $where ticket_code = '".$ticket_code."' ";
			$sql='SELECT * FROM ' . T_TICKET . $search_value ;
			$ticket = DB::fetch($sql);
			if($ticket){
				$valUpdate = array(
					'ticket_value' => $ticket_value,
					'approved_code' => $this->genCouponCode(3, array(), '0123456789'), //Ma xac nhan de thuong gold cho khach
					'time_using' => TIME_NOW,
					'status' => 1,
					'approved_user' => User::username()
				);
				if(DB::update('ticket', $valUpdate, " $where ticket_code='".$ticket['ticket_code']."' AND endTime>".TIME_NOW)){
					return 'success';
				}
			}
		}
	}
	
	function genCouponCode($length = 6, $exist=array(), $characters='0123456789abcdefghjkmnpqrstuvwxyz'){
		$characters = str_repeat($characters,$length);
		$string = substr(str_shuffle($characters), 0, $length);
		if(in_array($string, $exist)){
			Coupon::genCouponCode($length, $exist, $characters);
		}else{
			return $string;
		}
	}
	
	function home(){
		global $display;
		if(User::is_login()){
			$return = $this->listTicket();
		}
		else{
			Url::redirect('login');
		}
		echo $return;
	}
	
}
?>